﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;
using System.IO;
using System.Text;
using Microsoft.SharePoint.Utilities;
using ConsolidationTool.Common;
using System.Collections.Generic;
using System.Collections;
using ConsolidationTool.WebParts.ControlTemplates.ConsolidationTool.WebParts;

namespace ConsolidationTool.WebParts.Layouts.CReport
{
    public partial class MBRView : FSReportBase
    {
        public string MBRLink
        {
            get
            {
                if (isMerge)
                    return "MergeLink";
                else
                    return "Link";
            }
        }
        public override ControlTemplates.CommonEntitySelector TopSelector
        {
            get
            {
                return commonEntitySelector as ControlTemplates.CommonEntitySelector;
            }
        }

        public override void GenerateReport_Click(object sender, EventArgs e)
        {
         

            SPList list = SPContext.Current.Web.Lists["MBRMaping"];
            var items = list.GetItems(new SPQuery()
            {
                Query = @"<Where>
      <Eq>
         <FieldRef Name='MBR' />
         <Value Type='Boolean'>1</Value>
      </Eq>
   </Where>
   <OrderBy>
      <FieldRef Name='NO' Ascending='True' />
   </OrderBy>"
            });

            if (isMerge) {
                items = list.GetItems(new SPQuery()
                {
                    Query = @"<Where>
                                  <Eq>
                                     <FieldRef Name='MergeReport' />
                                     <Value Type='Boolean'>1</Value>
                                  </Eq>
                               </Where>
                               <OrderBy>
                                  <FieldRef Name='NO' Ascending='True' />
                               </OrderBy>"
                });
            }

            int itemCount = items.Count;
            string parametter = CreateCurrentParametter();
            string siteUrl = SPContext.Current.Site.WebApplication.AlternateUrls[0].IncomingUrl;
            var crawlEngine = new CrawlEngine();
            var titleList = new ArrayList();
            var tableSource = new Dictionary<string, string>();

            for (int i = 0; i < itemCount; i++)
            {
                var item = items[i];
                string title = item["NO"] + " " + item["Title"] + "";
                string link = CommbieUrl(siteUrl, item[MBRLink] + "", parametter);
                string trimTitle = Guid.NewGuid().ToString();
                string tmp = RequestPageSource(link);
                string commonTable = crawlEngine.Crawl(tmp);

                commonTable = commonTable.Replace("\"commontable\"", "\"commontable\" name='" + title + "'");
                titleList.Add(new { identity = trimTitle, link = link, title = title });
                tableSource.Add(trimTitle, commonTable);
            }

            rpTitle.DataSource = titleList;
            rpTitle.DataBind();
            rpTable.DataSource = tableSource;
            rpTable.DataBind();
        }

        private string CommbieUrl(string siteUrl, string p, string parametter)
        {
            string tmp = SPUtility.ConcatUrls(siteUrl, p);
            if (tmp.IndexOf('?') != -1)
                return tmp + "&" + parametter;

            return tmp + "?" + parametter;
        }

        private string CreateCurrentParametter()
        {
            return string.Format("automatic=true&year={0}&month={1}&cocd={2}&fullname={3}&currency={4}&tonnage={5}&hfullname={6}",
                TopSelector.yearTextBox.Text,
                TopSelector.monthTextBox.Text,
                TopSelector.lbCoCd.Text,
                TopSelector.lbCompanyFullName.Text,
                TopSelector.lbCompanyCurrency.Text,
                TopSelector.lbCompanyTonnage.Text,
                TopSelector.HFCompanyFullName.Value);
        }

        public string RequestPageSource(string strURL)
        {

            string tmp = string.Empty;
         
            System.Net.HttpWebRequest request = null;
         System.Net.HttpWebResponse objWebResponse = null;
         System.IO.StreamReader streamReader = null;
     
        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object s, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };
                              
        request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strURL);
         request.Method = "GET";

         request.UseDefaultCredentials = true;

         request.PreAuthenticate = true;

         request.Credentials = CredentialCache.DefaultCredentials;

   //      request.Credentials = CredentialCache.DefaultNetworkCredentials;// new System.Net.NetworkCredential("mike", "`1qaz2wsx", "reqeutte");// System.Net.CredentialCache.DefaultCredentials;
         
        objWebResponse = (System.Net.HttpWebResponse)request.GetResponse();
  
        streamReader = new System.IO.StreamReader(objWebResponse.GetResponseStream());

        tmp = streamReader.ReadToEnd();
         
 
        streamReader.Close();
         objWebResponse.Close();
         request.Abort();
   
 

            //WebRequest wrequest = WebRequest.Create(strURL);
            //wrequest.UseDefaultCredentials = true;
            //wrequest.PreAuthenticate = true;
            //wrequest.Credentials = CredentialCache.DefaultCredentials;
            //WebResponse wresponse = wrequest.GetResponse();
            //Stream resStream = wresponse.GetResponseStream();
            //StreamReader sr = new StreamReader(resStream, Encoding.Default);
            //tmp = sr.ReadToEnd();
            //resStream.Close();
            //sr.Close();
            return tmp;
        }
    }
}
